package com.coder4j.platform.service;

import com.coder4j.platform.cache.OrganizationCache;
import com.coder4j.platform.cache.RoleCache;
import com.coder4j.platform.config.GlobalConfig;
import com.coder4j.starter.tools.vo.BaseException;
import com.coder4j.starter.web.BaseServiceImpl;
import com.coder4j.platform.cache.AuthCache;
import com.coder4j.starter.web.jwt.AuthVO;
import com.coder4j.starter.web.jwt.TokenUtils;
import com.coder4j.starter.web.util.AuthUtils;
import com.coder4j.platform.PasswordUtils;
import com.coder4j.platform.entity.AuthUserEntity;
import com.coder4j.platform.mapper.AuthUserMapper;
import com.coder4j.platform.vo.AuthUserQuery;
import com.coder4j.platform.vo.AuthUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户
 * @author keller
 * @date 2024-05-07 18:10:11
 */
@Service
@Slf4j
public class AuthUserService extends BaseServiceImpl<AuthUserMapper, AuthUserEntity, AuthUserVO> {

    @Resource
    private AuthUserMapper mapper;

    @Resource
    @Lazy
    private AuthCache authCache;

    @Resource
    @Lazy
    private AuthRefService refService;


    @Override
    public AuthUserVO entity2Vo(AuthUserEntity entity) {
        AuthUserVO vo = new AuthUserVO();
        BeanUtils.copyProperties(entity,vo);
        vo.setRoleName(RoleCache.getRoleName(vo.getRoleId()));
        vo.setOrganizationName(OrganizationCache.getOrganizationName(vo.getOrganizationId()));
        return vo;
    }

    @Override
    public AuthUserEntity vo2Entity(AuthUserVO vo) {
        AuthUserEntity entity = new AuthUserEntity();
        BeanUtils.copyProperties(vo, entity);
        return entity;
    }

    public void addUser(AuthUserVO userVO) {
        AuthUserEntity userEntity = this.vo2Entity(userVO);
        userEntity.setPassword(PasswordUtils.encrypt(GlobalConfig.DEFAULT_PASSWORD));

        this.baseSave(userEntity);
    }

    public void resetPassword(Long userId) {
        AuthUserEntity user = this.baseGetById(userId);
        if(user == null){
            throw BaseException.noData();
        }
        user.setPassword(PasswordUtils.encrypt(GlobalConfig.DEFAULT_PASSWORD));
        this.baseSave(user);
    }


    /**
     * 用户重置密码
     *
     * @param vo
     */
    public void resetPassword(AuthUserVO vo) {
        AuthUserEntity user = this.baseGetById(vo.getId());
        if (user == null) {
            throw BaseException.noData();
        }
        user.setPassword(PasswordUtils.encrypt(vo.getPassword()));
        this.baseSave(user);
    }


    public AuthVO register(String account,String password){
        AuthUserQuery query = new AuthUserQuery();
        query.setAccountNo(account);
        AuthUserEntity user = this.baseQueryOne(query);
        if(user != null){
            throw BaseException.error("账号已存在");
        }
        user = new AuthUserEntity();
        user.setAccountNo(account);
        user.setUserName(account);
        user.setNickName(account);
        user.setPassword(PasswordUtils.encrypt(password));
        user.setRoleId(GlobalConfig.DefaultRoleId);
        this.baseSave(user);

        return this.login(account,password);

    }

    public AuthVO login(String account,String password) {
        AuthUserQuery query = new AuthUserQuery();
        query.setAccountNo(account);
        AuthUserEntity user = this.baseQueryOne(query);
        if(user == null){
            throw BaseException.noData();
        }
        boolean checked = PasswordUtils.checkPassword(password, user.getPassword());
        if(!checked){
            throw BaseException.error("账号密码错误");
        }
        Long userId = user.getId();
        AuthVO vo = this.buildAuthVO(user);

        authCache.cacheAuthUser(userId,vo);
        return vo;
    }

    public AuthVO buildAuthVO(AuthUserEntity user) {
        AuthVO vo = new AuthVO();
        vo.setUserId(user.getId());
        vo.setUserName(user.getUserName());
        vo.setNickName(user.getNickName());
        vo.setEmail(user.getEmail());
        vo.setPhone(user.getPhone());

        vo.setOrgId(user.getOrganizationId());
        vo.setOrgName(OrganizationCache.getOrganizationName(user.getOrganizationId()));
        vo.setOrgPath(OrganizationCache.getOrganizationPath(user.getOrganizationId()));

        vo.setRoleId(user.getRoleId());
        vo.setRoleName(RoleCache.getRoleName(user.getRoleId()));
        //查询角色的数据范围
        vo.setDataScope(RoleCache.getDataScope(user.getRoleId()));
        if(user.getRoleId() != null){
            vo.setRights(RoleCache.getRights(user.getRoleId()));
            vo.setButtons(RoleCache.getButtonList(user.getRoleId()));
        }

        String token = TokenUtils.buildToken(vo);
        vo.setToken(token);
        return vo;
    }

    public void logout() {
        AuthVO authVO = AuthUtils.getAuthVO();
        if(authVO == null){
            return;
        }
        Long userId = authVO.getUserId();
        authCache.removeAuthUserCache(userId);

    }


    public void editUser(AuthUserVO vo) {

        Long userId = vo.getId();

        AuthUserEntity user = this.baseGetById(userId);

        // 可以修改的内容：用户名、昵称、邮箱、手机号、角色、部门

        user.setUserName(vo.getUserName());
        user.setNickName(vo.getNickName());
        user.setEmail(vo.getEmail());
        user.setPhone(vo.getPhone());
        user.setRoleId(vo.getRoleId());
        user.setOrganizationId(vo.getOrganizationId());

        this.baseSave(user);

    }
}
